﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web.Mvc;
using Lu.Blog.Domain.Factory;
using Lu.Blog.Domain.Model.DocumentType;
using Lu.Blog.Domain.Utils;
using Lu.Blog.Models;
using umbraco;
using umbraco.MacroEngines;
using Umbraco.Web.Mvc;
using Vega.USiteBuilder;

namespace Lu.Blog.Controllers
{
    public class CommonSurfaceController : SurfaceController
    {
        //
        // GET: /CommonSurface

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Footer()
        {
            IEnumerable<ContentPage> childrenContentPage = from i in new DynamicNode(-1).Descendants()
                where i.NodeTypeAlias == "ContentPage"
                select ContentHelper.GetByNodeId<ContentPage>(i.Id);

            IEnumerable<PostShortcut> posts = from i in childrenContentPage
                orderby i.CreateDate descending
                select
                    new PostShortcut
                    {
                        Date = i.CreateDate,
                        Title = (!string.IsNullOrEmpty(i.NavigationTitle) ? i.NavigationTitle : i.PreviewTitle),
                        Link = i.NiceUrl,
                        ImageUrl = (!string.IsNullOrEmpty(i.PreviewImage) ? XmlNodePickerHelper.GetImagesFromPicker(i.PreviewImage).FirstOrDefault().NiceUrl : "")
                    };

            var categories = from c in BlogContentHelper.GetAllNonEmptyCategories() orderby c.Children.Count() descending select new CategoryShortcut()
            {
                Link = c.NiceUrl,
                Label = c.Label
            };

            string about = String.Empty;
            var homepage = BlogContentHelper.GetRoot().ChildrenAsList.First(i => i.NodeTypeAlias == "HomePage");
            if (homepage.HasProperty("about"))
            {
                about = homepage.GetProperty("about").Value;
            }

            var viewModel = new FooterViewModel
            {
                Categories = categories,
                Posts = posts.Take(3),
                AboutText = about
            };
            return PartialView("Footer", viewModel);
        }
    }
}